<template>
  <view class="info-container">
    <u-navbar :title="title" left-icon="arrow-left" left-icon-color="#303133" bg-color="#ffffff" fixed placeholder
      @left-click="back" />

    <!-- 账户信息卡片 -->
    <view class="info-card">
      <view class="info-item">
        <view class="info-label">账户信息</view>
      </view>

      <view class="form-item">
        <view class="form-label">用户头像</view>
        <view class="avatar-container" @click="chooseAvatar">
          <u-avatar :src="userInfo.avatar" size="60" mode="circle"></u-avatar>
          <view class="edit-mask">
            <u-icon name="camera" size="20" color="#fff" />
          </view>
        </view>
      </view>

      <view class="form-item" @click="openNameDialog">
        <view class="form-label">真实姓名</view>
        <view class="form-value">
          <text>{{ userInfo.name || "请输入真实姓名" }}</text>
          <view class="edit-icon-container">
            <u-icon name="/static/edit-line.png" size="16" color="#999" class="arrow-icon"></u-icon>
          </view>
        </view>
      </view>
    </view>

    <!-- 测试按钮 -->
    <!-- <button @click="openNameDialog">测试打开弹窗</button> -->

    <!-- 公司信息卡片 -->
    <view class="info-card" style="margin-top: 20rpx">
      <view class="info-item">
        <view class="info-label">公司信息</view>
      </view>

      <view class="form-item">
        <view class="form-label">职位名称</view>
        <view class="form-value">{{ userInfo.jobName }}</view>
      </view>

      <view class="form-item">
        <view class="form-label">公司名称</view>
        <view class="form-value">{{ userInfo.corpName }}</view>
      </view>
    </view>

    <!-- 移除u-popup组件，使用原生弹窗 -->
  </view>
</template>

<script setup>
import { ref } from "vue";
// 使用ES模块导入语法
import { navigate as publicNavigate } from "@/utils/public.js";
import * as Auth from '@/api/auth.js'
import server from '@/utils/config.js'
console.log(server)
// 模拟数据
const userAvatar = ref("/static/logo.png");
const realName = ref("xxxxxxxx");
const title = ref("用户信息");
const userInfo = ref({
    id: 0,
    avatar: "/static/logo.png",
    name: "张三",
    jobName: "软件工程师",
    corpName: "上海XX科技有限公司",
});
// 编辑相关变量
const nameDialogShow = ref(false);
const newName = ref("");

const back = () => {
  publicNavigate("back");
};

// 选择头像
const chooseAvatar = () => {
  uni.chooseImage({
    count: 1,
    sizeType: ["original", "compressed"],
    sourceType: ["album", "camera"],
    success: (res) => {
      const tempFilePath = res.tempFilePaths[0];
      // 显示加载中提示
      uni.showLoading({
        title: '上传中...',
      });
      // 调用上传接口
      new Promise((resolve, reject) => {
        uni.uploadFile({
          url: server.api + '/user/upload', // 上传接口地址
          filePath: tempFilePath,
          header: {
            'Authorization': 'Bearer ' + uni.getStorageSync('token')
          },
          name: 'file', // 文件参数名，需与后端接口保持一致
          success: (uploadFileRes) => {
            try {
              // 解析服务器返回的JSON数据
              const resUpload = JSON.parse(uploadFileRes.data);
              if (resUpload.code == 200) {
                resolve(resUpload);
              } else {
                reject(new Error(resUpload.msg || '上传失败'));
              }
            } catch (e) {
              reject(new Error('上传失败，返回数据格式错误'));
            }
          },
          fail: (error) => {
            reject(new Error('上传失败，请检查网络'));
          },
          complete: () => {
            // 隐藏加载提示
            uni.hideLoading();
          }
        });
      }).then(resUpload => {
        // 上传成功，获取服务器返回的文件路径
        // 注意：请根据实际API返回结构调整字段名称
        console.log(resUpload)
        const avatarUrl = server.api + "/" + resUpload.data.path.replace("\\", "/"); // 假设服务器返回的文件路径字段为path
        // 更新用户信息
        return Auth.updateInfo({
          id: userInfo.value.id,
          avatar: avatarUrl
        });
      })
        .then(resUpdate => {
          if (resUpdate.code == 200) {
            uni.showToast({
              title: '修改成功',
              icon: 'success'
            });
            flushInfo(); // 刷新用户信息
          }
        })
        .catch(error => {
          // 隐藏加载提示
          uni.hideLoading();
          
          uni.showToast({
            title: error.message || '上传失败，请重试',
            icon: 'none'
          });
          console.error('头像上传失败:', error);
        });
    },
  });
};

// 打开姓名编辑弹窗
const openNameDialog = () => {
  console.log("打开编辑弹窗");
  newName.value = userInfo.value.name || "";
  // 使用uni-app原生弹窗
  uni.showModal({
    title: "编辑姓名",
    editable: true,
    placeholderText: "请输入真实姓名",
    content: newName.value, // 使用content属性设置初始值
    success: (res) => {
      if (res.confirm) {
        const val =  res.content.trim();
        if (val) {
          Auth.updateInfo({
            id: userInfo.value.id,
            name: val,
          }).then(res2 => {
            if (res2.code == 200) {
              uni.showToast({
                title: '修改成功',
                icon: 'success'
              });
              userInfo.value.name = val;
            }
          })
          flushInfo()
        } else {
          uni.showToast({
            title: "请输入真实姓名",
            icon: "none",
          });
        }
      }
    },
  });
};
const flushInfo = () => {
  Auth.getInfo().then(res => {
    if (res.code == 200) {
      // console.log(res.data)
      uni.setStorageSync('userInfo', JSON.stringify(res.data));
      // console.log("userInfo", uni.getStorageSync('userInfo'));
      userInfo.value = res.data.info
    }
  })
}
flushInfo()
// 保存姓名方法不再需要，已整合到openNameDialog中
</script>

<style scoped>
.info-container {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.header {
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  border-bottom: 1rpx solid #eee;
  margin-bottom: 20rpx;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.info-card {
  margin: 20rpx;
  background-color: #fff;
  border-radius: 16rpx;
  overflow: hidden;
}

.info-item {
  padding: 24rpx 30rpx;
}

.info-label {
  font-size: 36rpx;
  color: #333;
  font-weight: bold;
}

.avatar-container {
  display: flex;
  align-items: center;
  position: relative;
}

.edit-mask {
  position: absolute;
  bottom: 0;
  right: 0;
  width: 24px;
  height: 24px;
  background-color: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 移除多余的样式 */

/* 弹窗样式 */
.dialog-content {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
}

.dialog-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  text-align: center;
  margin-bottom: 30rpx;
}

.dialog-input {
  margin-bottom: 30rpx;
}

.dialog-buttons {
  display: flex;
  justify-content: space-between;
}

.dialog-buttons u-button {
  width: 45%;
}

.form-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
}

.form-label {
  font-size: 30rpx;
  color: #999;
}

.form-value {
  font-size: 30rpx;
  color: #666;
  display: flex;
  align-items: center;
}

.arrow-icon {
  margin-left: 10rpx;
}

.edit-icon-container {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
}
</style>